import config from '../config'
import model from '../model/tank'
import position from '../service/position'
import CanvasAbstract from './canvasAbstract'

class Tank extends CanvasAbstract implements ICanvas {
  intervalId: number = 0

  num(): number {
    return config.tank.num
  }
  model(): ModelConstructor {
    return model
  }

  // 这里的render方法在main.ts文件中执行了
  render(): void {
    // 注意调用顺序，先创建，后渲染
    this.createModels()
    // super.renderModels()
    // tank需要动态渲染
    this.intervalId = setInterval(() => this.renderModels(), config.timeout)
  }

  // 覆写父类的方法
  protected createModels() {
    for (let i = 0; i < this.num(); i++) {
      const pos = position.generatePosition()
      const model = this.model()
      const instance = new model(pos.x, 0)
      this.models.push(instance)
    }
  }

  renderModels() {
    // 清除
    this.ctx.clearRect(0, 0, config.canvas.width, config.canvas.height)

    // 调用父类的渲染
    super.renderModels()
  }

  stop() {
    clearInterval(this.intervalId)
  }
}

export default new Tank('tank')
